const dbModel = require("../lib/sql");
const { sendCode } = require("../controller/sendCode");
const { randomString } = require("../lib/random");
let { jiami, jiemi } = require("../lib/bcrypto");
const fs = require("fs");
const path = require("path");

const { JWT } = require("../jwt");

let code = new Map();
//注册用户
exports.insertUser = async (req, res) => {
  let data = req.body;
  //在这里搜索一下用户看看用户是否存在
  const isUsername = await dbModel.selectUser(data.username);
  const isUseremail = await dbModel.selectEmail(data.email);
  if (isUsername.length > 0) {
    res.send({
      code: 305,
      message: "用户名已存在",
    });
  } else if (isUseremail.length > 0) {
    res.send({
      code: 306,
      message: "邮箱已被注册",
    });
  } else {
    //判断验证码是否一致
    if (!code.get(data.email)) {
      res.send({ code: 310, message: "验证码已过期或没发送" });
    } else {
      if (data.sms == code.get(data.email)) {
        //注册
        await dbModel
          .insertUser([data.username, jiami(data.password), data.email])
          .then((result) => {
            res.send({
              code: 200,
              message: result,
            });
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        res.send({
          code: 320,
          message: "验证码不正确",
        });
      }
    }
  }
};

//发送验证码
exports.sendCode = async (req, res) => {
  let data = req.body;
  const isUseremail = await dbModel.selectEmail([data.email]);
  //注册
  if (data.new == 1) {
    if (isUseremail.length > 0) {
      res.send({
        code: 306,
        message: "邮箱已存在",
      });
    } else {
      //注册

      code.set(data.email, randomString());
      setTimeout(() => {
        code.delete(data.email);
      }, 600000);

      sendCode(data.email, code.get(data.email));
      res.send({
        code: 201,
        message: "验证码发送成功",
      });
    }
  } else {
    if (isUseremail.length > 0) {
      console.log(1);
      code.set(data.email, randomString());
      setTimeout(() => {
        code.delete(data.email);
      }, 600000);

      sendCode(data.email, code.get(data.email));
      res.send({
        code: 201,
        message: "验证码发送成功",
      });
    } else {
      console.log("邮箱未注册");
      res.send({
        code: 325,
        message: "邮箱未注册",
      });
    }
  }
};

//登录用户

exports.loginUser = async (req, res) => {
  let data = req.body;
  dbModel.selectEmail([data.email]).then(async (result) => {
    // console.log(result);
    if (result.length > 0) {
      if (result[0].is_banned) {
        res.send({
          code: 325,
          message: "账号已被封禁",
        });
      } else {
        if (jiemi(data.password, result[0].password)) {
          let userid = await dbModel.emailselectuserid(data.email);
          let level = await dbModel.selectPermission(userid[0].userid);
          let branch = await dbModel.selectBranch([
            userid[0].userid,
            userid[0].userid,
            null,
            null,
          ]);

          const info = JSON.stringify({
            userid: result[0].userid,
            username: result[0].username,
            Permission: level[0].permission,
            branch: branch[0].branch,
          });
          const arr = [];
          for (let i of info) {
            arr.push(i.codePointAt());
          }
          const token = JWT.generate({ message: arr }, "24h");
          // console.log(token)
          // console.log(token.split('.')[1]);
          // console.log(token);
          //后端返回 也直接弄到header中
          // res.header('Authorization',token);
          res.header({
            //设置开放的请求头中的这个字段
            "Access-Control-Expose-Headers": "Authorization",
            //给请求头添加内容
            Authorization: token,
          });

          res.json({
            ...result[0],
            code: 205,
            message: "登录成功",
          });
        } else {
          res.send({
            code: 315,
            message: "密码错误",
          });
        }
      }
    } else {
      res.send({
        code: 325,
        message: "邮箱不存在",
      });
    }
  });
};
//找回用户修改密码
exports.searchUser = async (req, res) => {
  let data = req.body;

  if (!code.get(data.email)) {
    res.send({ code: 310, message: "验证码已过期或没发送" });
  } else {
    //判断邮箱是否存在
    if (data.sms == code.get(data.email)) {
      await dbModel
        .updatepass([jiami(data.password), data.email])
        .then((result) => {
          res.send({
            code: 203,
            message: "密码修改成功",
          });
        });
    } else {
      res.send({
        code: 320,
        message: "验证码不正确",
      });
    }
  }
};

//showCard  显示默认卡片内容

exports.showCard = async (req, res) => {
  let data = req.query;
  await dbModel.showCard([data.branch, data.type]).then((result) => {
    res.send({
      code: 200,
      data: result,
    });
  });
};

//显示默认评论
exports.showComment = async (req, res) => {
  let data = req.query;

  await dbModel.showComment([data.postid]).then((result) => {
    res.send({
      code: 200,
      message: result,
    });
  });
};

//addcard  发布新帖子

exports.addCard = async (req, res) => {
  const data = req.body;
  const values = [
    data.userid,
    data.username,
    data.label,
    data.color,
    data.message,
  ];
  if (req.file) {
    values.push(req.file.filename);
    values.push(req.file.path);
  } else {
    values.push(null);
    values.push(null);
  }
  if (data.school) {
    values.push(data.school);
  } else {
    values.push(null);
  }
  await dbModel.selectPermission([values[0]]).then((resultp) => {
    dbModel.selectCardCount([values[0]]).then((resultthree) => {
      if (resultthree[0]) {
        if (
          resultthree[0].daily_posts < 10 ||
          resultp[0].permission == "Level1"
        ) {
          dbModel.addCard(values).then((result) => {
            dbModel.selectCard([result.insertId]).then((resulttwo) => {
              res.send({
                ...resulttwo[0],
                code: 200,
                message: "发布成功,审核后将会显示",
              });
            });
          });
        } else {
          if (req.file) {
            fs.unlinkSync(req.file.path);
          }
          res.send({
            code: 355,
            message: "每天最多发十条哈",
          });
        }
      } else {
        res.send({
          code: 355,
          message: "登陆异常,退出重新登录",
        });
      }
    });
  });
};

//用户喜欢反馈

exports.changefeedbacks = async (req, res) => {
  const data = req.body;

  await dbModel
    .changefeedbacks([
      data.userid,
      data.postid,
      data.like,
      data.useredid,
      data.like,
    ])
    .then((result) => {
      res.send({
        like: data.like,
      });
    });
};

//用户是否喜欢

exports.userLike = async (req, res) => {
  const data = req.query;
  await dbModel.userLike([data.userid, Boolean(data.like)]).then((result) => {
    const postid = result.map((res) => res.postid);
    res.send({
      postid: postid,
    });
  });
};

//用户举报反馈

exports.changefeedbacksreport = async (req, res) => {
  const data = req.body;

  await dbModel
    .changefeedbacksreport([data.userid, data.postid, data.report, data.report])
    .then((result) => {
      res.send({
        report: data.report,
      });
    });
};

//用户是否举报

exports.userReport = async (req, res) => {
  const data = req.query;
  await dbModel
    .userReport([data.userid, Boolean(data.report)])
    .then((result) => {
      const postid = result.map((res) => res.postid);
      res.send({
        postid: postid,
      });
    });
};
//添加评论
exports.addCommit = async (req, res) => {
  const data = req.body;
  let count = await dbModel.dailycount([data.userid]);
  if (count[0].daily_comments <= 30) {
    await dbModel
      .addCommit([
        data.userid,
        data.username,
        data.postid,
        data.commitcontent,
        data.useredid,
      ])
      .then((result) => {
        dbModel.selectCommit([result.insertId]).then((result) => {
          res.send({
            code: 200,
            data: result[0],
          });
        });
      });
  } else {
    res.send({
      code: 300,
      data: "评论次数以达到30次上限",
    });
  }
};

//删除卡片(优化后)
exports.deleteCard = async (req, res) => {
  const data = req.body;
  const image_name = await dbModel.selectPicturePath([data.postid]);
  await dbModel.selectUserid([data.postid]).then((result) => {
    if (result[0].userid == data.userid) {
      dbModel.deleteCard([data.postid]).then((result) => {
        res.send({
          code: 200,
          message: "删除成功",
        });
        if (image_name.length > 0 && image_name[0].image_name !== "默认.png") {
          const filePath = path.join(
            path.resolve(__dirname, "../"),
            "data/uploads/img",
            image_name[0].image_name
          );
          if (fs.existsSync(filePath)) {
            fs.unlink(filePath, (err) => {
              if (err) {
                console.error("Error deleting file:", err);
              } else {
                console.log("File deleted successfully:", filePath);
              }
            });
          } else {
            console.log("File does not exist:", filePath);
          }
        }
      });
    } else {
      dbModel.selectPermission([data.userid]).then((resultp) => {
        if (resultp[0].permission == "Level1") {
          dbModel.deleteCard([data.postid]).then((result) => {
            res.send({
              code: 200,
              message: "使用站长权限删除成功",
            });
            if (
              image_name.length > 0 &&
              image_name[0].image_name !== "默认.png"
            ) {
              const filePath = path.join(
                path.resolve(__dirname, "../"),
                "data/uploads/img",
                image_name[0].image_name
              );
              if (fs.existsSync(filePath)) {
                fs.unlink(filePath, (err) => {
                  if (err) {
                    console.error("Error deleting file:", err);
                  } else {
                    console.log("File deleted successfully:", filePath);
                  }
                });
              } else {
                console.log("File does not exist:", filePath);
              }
            }
          });
        } else if (resultp[0].permission == "Level2") {
          dbModel
            .selectBranch([data.userid, data.userid, null, null])
            .then((userbranch) => {
              dbModel
                .selectBranch([null, null, data.postid, data.postid])
                .then((postbranch) => {
                  if (userbranch[0].branch == postbranch[0].branch) {
                    dbModel.deleteCard([data.postid]).then((result) => {
                      res.send({
                        code: 200,
                        message: "使用管理员权限删除成功",
                      });
                      if (
                        image_name.length > 0 &&
                        image_name[0].image_name !== "默认.png"
                      ) {
                        const filePath = path.join(
                          path.resolve(__dirname, "../"),
                          "data/uploads/img",
                          image_name[0].image_name
                        );
                        if (fs.existsSync(filePath)) {
                          fs.unlink(filePath, (err) => {
                            if (err) {
                              console.error("Error deleting file:", err);
                            } else {
                              console.log(
                                "File deleted successfully:",
                                filePath
                              );
                            }
                          });
                        } else {
                          console.log("File does not exist:", filePath);
                        }
                      }
                    });
                  }
                });
            });
        } else {
          res.send({
            code: 300,
            message: "你没有权限删除此帖子",
          });
        }
      });
    }
  });
};

//搜索卡片

exports.inputSelectCard = async (req, res) => {
  let data = req.query;
  if (data.type == "username") {
    if (data.branch == "主留言墙") {
      await dbModel
        .inputSelectCard([null, null, null, data.value, data.value, null])
        .then((result) => {
          res.send({
            code: 200,
            message: result,
          });
        });
    } else {
      await dbModel
        .inputSelectCard([
          null,
          null,
          null,
          data.value,
          data.value,
          data.branch,
        ])
        .then((result) => {
          res.send({
            code: 200,
            message: result,
          });
        });
    }
  } else if (data.type == "postid") {
    if (data.branch == "主留言墙") {
      await dbModel
        .inputSelectCard([data.value, data.value, null, null, null, null])
        .then((result) => {
          res.send({
            code: 200,
            message: result,
          });
        });
    } else {
      await dbModel
        .inputSelectCard([
          data.value,
          data.value,
          data.branch,
          null,
          null,
          null,
        ])
        .then((result) => {
          res.send({
            code: 200,
            message: result,
          });
        });
    }
  }
};

//获取follow信息

exports.selectFollow = async (req, res) => {
  let data = req.query;
  //两种传值
  if (data.username) {
    var userid = dbModel.selectUseridthree([data.username]);
  } else {
    var userid = dbModel.selectUseridtwo([data.postid]);
  }
  userid.then((result) => {
    if (result.length > 0)
      dbModel.selectfensi([result[0].userid]).then((resultfensi) => {
        dbModel.selectguanzhu([result[0].userid]).then((resultguanzhu) => {
          if (resultfensi.length !== 0 && resultguanzhu.length !== 0) {
            res.send({
              code: 200,
              userid: result[0].userid,
              message: "follow返回成功",
              fensiId: resultguanzhu,
              guanzhuId: resultfensi,
            });
          } else if (resultguanzhu.length == 0) {
            res.send({
              code: 200,
              userid: result[0].userid,
              message: "follow返回成功",
              fensiId: [],
              guanzhuId: resultfensi,
            });
          } else if (resultfensi.length == 0) {
            res.send({
              code: 200,
              userid: result[0].userid,
              message: "follow返回成功",
              fensiId: resultguanzhu,
              guanzhuId: [],
            });
          } else {
            res.send({
              code: 200,
              message: "follow返回成功",
              userid: result[0].userid,
              fensiId: [],
              guanzhuId: [],
            });
          }
        });
      });
  });
};

//增添关注用户
exports.guanzhuT = async (req, res) => {
  let data = req.body;
  await dbModel.guanzhuT([data.followerid, data.followedid]).then((result) => {
    res.send({
      code: 200,
      message: "关注成功",
    });
  });
};

//删除关注记录（取消关注用户）

exports.guanzhuF = async (req, res) => {
  let data = req.body;
  await dbModel.guanzhuF([data.followerid, data.followedid]).then((result) => {
    res.send({
      code: 200,
      message: "删除成功",
    });
  });
};

//用户帖子的数量

exports.usercardCount = async (req, res) => {
  let data = req.query;
  await dbModel.usercardCount([data.userid]).then((result) => {
    res.send({
      code: 200,
      data: result,
    });
  });
};
//更新用户头像
exports.userhead = async (req, res) => {
  let data = req.body;
  const useravatar = await dbModel.selectavar([data.userid]);
  let resultcount = await dbModel.change_count([data.userid]);
  if (resultcount[0].change_count < 15) {
    if (useravatar[0].avatar !== "默认.png") {
      const filePath = path.join(
        path.resolve(__dirname, "../"),
        "data/uploads/userimg",
        useravatar[0].avatar
      );
      if (fs.existsSync(filePath)) {
        fs.unlink(filePath, (err) => {
          if (err) {
            console.error("Error deleting file:", err);
          } else {
            console.log("File deleted successfully:", filePath);
          }
        });
      } else {
        console.log("File does not exist:", filePath);
      }
    }
    await dbModel
      .updateAvatar([req.file.filename, data.userid])
      .then(() => {
        res.send({
          code: 200,
          data: req.file.filename,
          message: "更换头像成功",
          count: 15 - resultcount[0].change_count - 1,
        });
      })
      .catch(() => {
        res.send({ code: 400, message: "头像修改失败" });
      });
  } else {
    //删除刚刚添加的图片
    const filePath = path.join(
      path.resolve(__dirname, "../"),
      "data/uploads/userimg",
      req.file.filename
    );
    if (fs.existsSync(filePath)) {
      fs.unlink(filePath, (err) => {
        if (err) {
          console.error("Error deleting file:", err);
        } else {
          console.log("File deleted successfully:", filePath);
        }
      });
    } else {
      console.log("File does not exist:", filePath);
    }
    res.send({ code: 400, message: "已经达到15次,等待下个月再修改吧" });
  }
};
//查询所有用户数据
exports.selectuserall = async (req, res) => {
  const data = req.query;
  const value = dbModel.selectuserall([data.userid]);
  value
    .then((result) => {
    
      res.json(result[0]);
    })
    .catch((err) => {
      console.log(err);
    });
};
//背景图片
exports.bgcpicture = async (req, res) => {
  let data = req.body.userid;
  let filename = req.file.filename;
  const userbgcpicture = await dbModel.selectbgcpicture([data]);
  let resultcount = await dbModel.change_count([data]);
  if (resultcount[0].change_count < 15) {
    if (userbgcpicture[0].background !== "默认.png") {
      const filePath = path.join(
        path.resolve(__dirname, "../"),
        "data/uploads/bgcimg",
        userbgcpicture[0].background
      );
      if (fs.existsSync(filePath)) {
        fs.unlink(filePath, (err) => {
          if (err) {
            console.error("Error deleting file:", err);
          } else {
            console.log("File deleted successfully:", filePath);
          }
        });
      } else {
        console.log("File does not exist:", filePath);
      }
    }
    let result = await dbModel.updatebgcpicture([filename, data]);

    if (result) {
      res.send({
        code: 200,
        data: filename,
        message: "更换背景成功",
        count: 15 - resultcount[0].change_count - 1,
      });
    } else {
      res.send({ code: 400, data: "背景修改失败" });
    }
  } else {
    //删除刚刚添加的图片
    const filePath = path.join(
      path.resolve(__dirname, "../"),
      "data/uploads/bgcimg",
      filename
    );
    if (fs.existsSync(filePath)) {
      fs.unlink(filePath, (err) => {
        if (err) {
          console.error("Error deleting file:", err);
        } else {
          console.log("File deleted successfully:", filePath);
        }
      });
    } else {
      console.log("File does not exist:", filePath);
    }
    res.send({ code: 400, data: "已经达到15次,等待下个月再修改吧" });
  }
};
//更新名称
exports.updatename = async (req, res) => {
  data = req.body;
  const isUsername = await dbModel.selectUser(data.username);
  let resultcount = await dbModel.change_count([data.userid]);
  if (isUsername.length > 0) {
    res.send({ code: 400, data: "用户名已存在" });
  } else {
    if (resultcount[0].change_count < 15) {
      const result = await dbModel.updatename([data.username, data.userid]);

      if (result) {
        res.send({
          code: 200,
          data: data.username,
          count: 15 - resultcount[0].change_count - 1,
        });
      } else {
        res.send({ code: 400, data: "姓名修改失败" });
      }
    } else {
      res.send({ code: 400, data: "已经达到15次,等待下个月再修改吧" });
    }
  }
};
//更新bio

exports.updatebio = async (req, res) => {
  try {
    data = req.body;
    let resultcount = await dbModel.change_count([data.userid]);
    if (resultcount[0].change_count < 15) {
      let result = await dbModel.updatebio([data.bio, data.userid]);

      if (result) {
        res.send({
          code: 200,
          data: "个性签名修改成功",
          count: 15 - resultcount[0].change_count - 1,
        });
      } else {
        res.send({ code: 400, data: "个性签名修改失败" });
      }
    } else {
      res.send({ code: 400, data: "已经达到15次,等待下个月再修改吧" });
    }
  } catch (error) {
    console.log("更新bio,updatebio" + error);
  }
};

//获取个人评论消息
exports.commentmessage = async (req, res) => {
  data = req.query;
  await dbModel
    .commentmessage([data.userid])
    .then((result) => {
      if (result.length > 0) {
        res.send({
          code: 200,
          data: result,
        });
      }
    })
    .catch((err) => {});
};

//删除评论消息

exports.deleteemessage = async (req, res) => {
  const data = req.body;
  dbModel
    .deleteemessage([data.commentid])
    .then((result) => {
      res.send({
        code: 200,
        data: data.commentid,
      });
    })
    .catch((err) => {});
};

//删除评论

exports.deletecomment = async (req, res) => {
  const data = req.query;
  let level = await dbModel.selectPermission([data.commentuserid]);
  let level1 = await dbModel.selectPermission([data.userid]);
  if (level.length > 0) {
    if (
      level[0].permission == "Level3" ||
      data.commentuserid == data.userid ||
      level1[0].permission == "Level1"
    ) {
      await dbModel
        .deletecomment([data.commentid, data.commentuserid])
        .then((result) => {
          res.send({
            code: 200,
          });
        })
        .catch((err) => {});
    } else {
      res.send({
        code: 300,
        message: "没有权限删除",
      });
    }
  }
};

//点赞消息反馈

exports.likemessage = async (req, res) => {
  const data = req.body;
  dbModel
    .likemessagecount(data.userid)
    .then((result) => {
      if (result.length > 0) {
        res.send({
          code: 200,
          message: result,
        });
      }
    })
    .catch((err) => {});
};

//删除点赞回复消息

exports.deletelikemessage = async (req, res) => {
  let data = req.body;

  dbModel
    .deletelikemessage(data.feedbacksid)
    .then((result) => {
      if (result.serverStatus == 2) {
        res.send({
          code: 200,
        });
      }
    })
    .catch((err) => {});
};

//获取粉丝关注消息

exports.fansmessage = async (req, res) => {
  try {
    const data = req.body;
    const result = await dbModel.fansmessage([data.userid]);
    if (result.length > 0) {
      res.send({
        code: 200,
        message: result,
      });
    }
  } catch (error) {
    console.log("获取粉丝消息,fansmessage", error);
  }
};

//删除粉丝关注消息
exports.deletefansmessage = async (req, res) => {
  try {
    const data = req.body;
    let result = await dbModel.deletefansmessage(data.id);

    if (result.serverStatus == 2) {
      res.send({
        code: 200,
      });
    }
  } catch (error) {
    console.log("删除粉丝消息,deletefansmessage", error);
  }
};

//获取系统消息

exports.systemmessage = async (req, res) => {
  const data = req.body;

  try {
    let result = await dbModel.selectsystemmessage(data.userid);
    if (result.length > 0) {
      res.send({
        code: 200,
        data: result,
      });
    }
  } catch (error) {
    console.log("获取系统消息,systemmessage", error);
  }
};

//删除系统消息
exports.deletesystemmessage = async (req, res) => {
  const data = req.body;

  let result = await dbModel.deletesystemmessage(data.message_id);

  if (result.serverStatus == 2) {
    res.send({
      code: 200,
    });
  }
};

//获取表信息

exports.getforms = async (req, res) => {
  const data = req.body.formname;
  try {
    let result = await dbModel.getforms([data]);
    if (result.length > 0) {
      res.send({
        code: 200,
        data: result,
      });
    }
  } catch (error) {
    console.log("获取表信息,getforms", error);
  }
};

//后台改变信息
exports.changeformvalue = async (req, res) => {
 const data = req.body;
  try {
   let result = await dbModel.changeformvalue([data,data.activeTabvalue,data.conditionvalue])
   if(result.serverStatus==2){
    res.send({
      code:200,
      message:'修改成功'
    })
   }
  } catch (error) {
    console.log("后端修改表信息,changeformvalue", error);
  }
};

//后台删除信息

exports.deleterowmessage = async (req, res) => {
  const data = req.body;
  try {
    let result = await dbModel.deleterowmessage([data,data.conditionvalue])
    if(result.serverStatus == 2){
      res.send({
        code:200,
        message:'删除成功'
      })
    }
  } catch (error) {
    console.log("后端删除表信息,deleterowmessage", error);
  }
}

//发送系统消息

exports.sendsystemmessage=async (req,res)=>{
  const data = req.body;

  try {
    let result =await dbModel.sendsystemmessage([data.userid,data.message])
    if(result.serverStatus == 2){
      res.send({
        code:200,
        message:'发布系统消息成功'
      })
    }
  } catch (error) {
    console.log("发布系统消息,sendsystemmessage", error);
  }
}